package com.etl.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.etl.constants.UserSession;
import com.etl.entity.EtlBusinessBatch;
import com.etl.entity.EtlBusinessDbInfo;
import com.etl.entity.EtlBusinessDbType;
import com.etl.enums.ResultEnum;
import com.etl.exception.GlobalException;
import com.etl.mapper.EtlBusinessBatchMapper;
import com.etl.mapper.EtlBusinessDbInfoMapper;
import com.etl.model.rev.DbInfoSaveUpdateRev;
import com.etl.service.IEtlBusinessDBInfoService;
import com.etl.util.AESUtil;
import com.etl.util.DbUntil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chaixuhong
 */
@Service
@Slf4j
public class EtlBusinessBusinessDbInfoInfoServiceImpl implements IEtlBusinessDBInfoService {

    @Resource
    private EtlBusinessDbInfoMapper etlBusinessDbInfoMapper;

    @Resource
    private EtlBusinessBatchMapper etlBusinessBatchMapper;



    // 处理一次类型转换，缓存到内存中，一次转换后会清空
    private List<EtlBusinessDbType> columeTypeTran;/*数据库之间字段类型转换*/

    /**
     * 查询数据库连接
     * @param
     */

    @Override
    public PageInfo<EtlBusinessDbInfo> getEtlBusinessDbInfoList(Integer pages, Integer sizes) {
        PageHelper.startPage(pages, sizes);
        QueryWrapper<EtlBusinessDbInfo> queryWrapper = new QueryWrapper<>();

        //普通用户的话,只能查询自己的任务
        if(UserSession.getUser().getUserType() == 0){
            queryWrapper.eq("create_account",UserSession.getUser().getAccountName());

        }
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("update_time");
        List<EtlBusinessDbInfo> list = etlBusinessDbInfoMapper.selectList(queryWrapper);
        PageInfo<EtlBusinessDbInfo> pageInfoDemo = new PageInfo<>(list);
        return pageInfoDemo;
    }


    /**
     * 添加数据库连接
     * @param dbInfoSaveUpdateRev
     */
    @Override
    public void saveUpdateEtlBusinessDbInfo( DbInfoSaveUpdateRev dbInfoSaveUpdateRev) {
        EtlBusinessDbInfo etlBusinessDbInfo = new EtlBusinessDbInfo();
        BeanUtils.copyProperties(dbInfoSaveUpdateRev,etlBusinessDbInfo);

        etlBusinessDbInfo.setPassword(AESUtil.encrypt(dbInfoSaveUpdateRev.getPassword(), AESUtil.password));

        if(dbInfoSaveUpdateRev.getDbId()!=null){
            //更新数据库信息
            QueryWrapper<EtlBusinessDbInfo> updateWrapper = new QueryWrapper<>();
            updateWrapper.eq("db_id", dbInfoSaveUpdateRev.getDbId());
            etlBusinessDbInfoMapper.update(etlBusinessDbInfo,updateWrapper);
            return;
        }
        /**
         * 1.查询数据库名是否存在
         */
        QueryWrapper<EtlBusinessDbInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("db_sysname", dbInfoSaveUpdateRev.getDbSysname());
        EtlBusinessDbInfo dbInfo = etlBusinessDbInfoMapper.selectOne(queryWrapper);
        if (dbInfo != null) {
            log.error("【添加数据库】{}", ResultEnum.DB_SYSTEM_NAME_EXIST.getErrMsg());
            throw new GlobalException(ResultEnum.DB_SYSTEM_NAME_EXIST);
        }
        /**
         * 2.添加数据库信息
         */
        etlBusinessDbInfo.setCreateAccount(UserSession.getUser().getAccountName());
        etlBusinessDbInfo.setCreateTime(new Date());
        etlBusinessDbInfo.setUpdateTime(new Date());
        etlBusinessDbInfoMapper.insert(etlBusinessDbInfo);
    }


    /**
     * 添加数据库连接
     */
    @Override
    public void deleteEtlBusinessDbInfo( Integer dbId) {


        LambdaQueryWrapper<EtlBusinessBatch> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.and(o -> o.eq(EtlBusinessBatch::getSourceDbId, dbId ).or().eq(EtlBusinessBatch::getTargetDbId, dbId ));
        List<EtlBusinessBatch> etlBusinessBatcheList = etlBusinessBatchMapper.selectList(lambdaQueryWrapper);
        if(etlBusinessBatcheList != null && etlBusinessBatcheList.size() >0){
            throw new GlobalException(0,"该数据库存在相关批次任务,不能进行删除");
        }

        EtlBusinessDbInfo etlBusinessDbInfo = new EtlBusinessDbInfo();
        etlBusinessDbInfo.setDbId(dbId);
        etlBusinessDbInfo.setStatus(0);
        etlBusinessDbInfoMapper.updateById(etlBusinessDbInfo);
    }


    /**
     * 测试数据库连接
     * @throws SQLException
     */
    @Override
    public void testDBConnection(DbInfoSaveUpdateRev dbInfoSaveUpdateRev) throws SQLException {
        EtlBusinessDbInfo dbInfo = new EtlBusinessDbInfo();
        BeanUtils.copyProperties(dbInfoSaveUpdateRev,dbInfo);
        //获取连接
        Connection conn = DbUntil.getConn(dbInfo);
        if (conn == null) {
            log.error("【测试数据库连接】{}", ResultEnum.DB_CONNECTION_ERROR.getErrMsg());
            throw new GlobalException(ResultEnum.DB_CONNECTION_ERROR);
        } else {
            //关闭数据库连接
            DbUntil.close(conn,null,null);
            //回收全局变量
            conn = null;
        }

    }



    @Override
    public List<String> querySystemName() {

        /**
         *  查询源数据库连接信息
         */
        QueryWrapper<EtlBusinessDbInfo> queryWrapper = new QueryWrapper<>();
        List<EtlBusinessDbInfo> dbNameList = etlBusinessDbInfoMapper.selectList(queryWrapper);
        List<String> nameList = new ArrayList<String>();
        for (EtlBusinessDbInfo dbInfo : dbNameList) {
            nameList.add(dbInfo.getDbSysname());
        }
        return nameList;
    }

}

